extends NodeState

@export var character : CharacterBody2D
@export var animated_sprite_2d : AnimatedSprite2D
@export var navigation_agent_2d : NavigationAgent2D
@export var max_speed : float = 100.0
@export var min_speed : float = 50.0

var speed: float


func _ready() -> void:
	navigation_agent_2d.velocity_computed.connect(velocity_computed)
	call_deferred("character_setup")
	

func character_setup() -> void :
	await get_tree().physics_frame
	#await get_tree().process_frame
	_configure_avoidance()
	set_movement_target()
	
	
func set_movement_target() -> void:
	var target_position : Vector2 = NavigationServer2D.map_get_random_point(navigation_agent_2d.get_navigation_map(),navigation_agent_2d.navigation_layers,false)
	navigation_agent_2d.target_position = target_position
	speed = randf_range(min_speed,max_speed)	

func _configure_avoidance() -> void:
	if navigation_agent_2d:
		navigation_agent_2d.avoidance_enabled = true
		var cs := character.get_node_or_null("CollisionShape2D") as CollisionShape2D
		if cs and cs.shape is CircleShape2D:
			navigation_agent_2d.radius = (cs.shape as CircleShape2D).radius
	
	
func _process(delta: float) -> void:
	if navigation_agent_2d.is_navigation_finished() or navigation_agent_2d.distance_to_target() <= 4.0:
		character.velocity = Vector2.ZERO
		return
		
	var target_position: Vector2 = navigation_agent_2d.get_next_path_position()
	var target_direction: Vector2 = character.global_position.direction_to(target_position)
	animated_sprite_2d.flip_h = target_direction.x < 0
	
	var velocity : Vector2 = target_direction * speed
	
	if navigation_agent_2d.avoidance_enabled:
		navigation_agent_2d.velocity = velocity
	else:
		character.velocity = velocity
		character.move_and_slide()
		

func velocity_computed(safe_velocity: Vector2) -> void:
	character.velocity = safe_velocity
	character.move_and_slide()
		
	
func _on_next_transitions() -> void:
	if navigation_agent_2d.is_navigation_finished() or navigation_agent_2d.distance_to_target() <= 4.0:
		# 到达目标点位，速度为0，切换到待机状态
		character.velocity = Vector2.ZERO
		transition.emit("idle")
		

func _on_enter() -> void:
	set_movement_target()
	animated_sprite_2d.play("run_right")

	
func _on_exit() -> void:
	animated_sprite_2d.stop()	
